<template>
  <div class="user-table">
    <div class="user-table-title-row">
      <span class="table-title">{{ title }}</span>
      <div v-if="!disabled" style="display: flex">
        <el-button type="primary" @click="downloadUserTemplate">模板下载</el-button>
        <el-upload action="#" :before-upload="beforeUpload">
          <el-button type="primary" style="margin: 0 10px;">导入</el-button>
        </el-upload>
        <el-button type="primary" @click="openInnerUserSelect">选择内部人员</el-button>
        <el-button type="primary" @click="openOuterUserSelect">添加外部人员</el-button>
        <slot name="rightcustom"></slot>
      </div>
    </div>
    <el-table :data="tableData" class="project-application-table">
      <el-table-column label="序号" prop="index" width="60">
        <template v-slot="{$index}">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="姓名" prop="name" min-width="100"/>
      <el-table-column label="性别" prop="sex" min-width="60"/>
      <el-table-column label="手机号" prop="telphone" min-width="120"/>
      <el-table-column label="身份证号" prop="idCard" min-width="120" show-overflow-tooltip/>
      <el-table-column label="特种作业资质" prop="specialJobType" min-width="140"
                       :formatter="(row, column, cellValue) => dicFormatter(options.specialOperationEnum, cellValue)"/>
      <el-table-column label="附件" prop="index" min-width="140">
        <template v-slot="{row}">
          <a v-for="item in row.documentInfi || []" :href="item.resourceAddress" target="_blank" style="color: #2F7DF1;">{{ item.enclosureContent }}</a>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" v-if="!disabled" fixed="right">
        <template v-slot="{row}">
          <el-button type="text" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" @click="$emit('ondelete', row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <AddInnerUser ref="innerRef" :options="options"/>
    <AddOuterUser ref="outerRef" :options="options" :operators="operators" :notRequireFile="notRequireFile"/>
  </div>
</template>

<script>
import AddInnerUser from "@/views/construction/project-application/componens/AddInnerUser";
import AddOuterUser from "@/views/construction/project-application/componens/AddOuterUser";
import {dicFormatter} from "@/views/construction/project-application/projectUtil";
import * as XLSX from 'xlsx/xlsx.mjs';

export default {
  name: "UserTable",
  components: {AddOuterUser, AddInnerUser},
  props: {
    title: {
      type: String
    },
    tableData: {
      type: Array,
      default: () => []
    },
    personType: undefined,
    options: {
      type: Object,
      default: () => ({})
    },
    disabled: {
      type: Boolean,
    },
    notRequireFile: {
      type: Boolean,
      default: false
    },
    operators: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      dicFormatter,
    }
  },
  computed: {},
  methods: {
    openInnerUserSelect() {
      // todo
      this.$refs.innerRef.open()
    },
    openOuterUserSelect() {
      this.$refs.outerRef.open({
        row: {personSource: this.options.personSourceEnum[1].value, personType: this.personType, documentInfi: []},
        resolve: (row) => {
          this.$emit('onsubmit', [row])
        }
      })
    },
    handleEdit(row) {
      if (row.personSource === this.options.personSourceEnum[1].value) {
        this.$refs.outerRef.open({
          row,
          resolve: (newRow) => {
            Object.assign(row, newRow)
          }
        })
      } else {
        // todo
        this.$refs.innerRef.open()
      }
    },
    downloadUserTemplate() {
      window.location.href = '/template/人员模板.xlsx'
    },
    beforeUpload(file) {
      // 读取Excel文件
      const reader = new FileReader();
      reader.onload = (event) => {
        const data = event.target.result;
        const workbook = XLSX.read(data, {type: 'binary'});

        // 获取工作表名并转换为数组
        const sheetNames = workbook.SheetNames;

        // 选中第一个工作表
        const selectedSheet = sheetNames[0];

        // 获取选中工作表的数据
        const sheetData = XLSX.utils.sheet_to_json(workbook.Sheets[selectedSheet]);
        let importList = sheetData.map((item, index) => {
          let specialJobType = item['特殊作业资质']
          if (this.personType !== this.options.personTypeEnum[1].value && !specialJobType) {
            this.$message.error(`第${index+2}行请选择特殊作业资质`)
            throw new Error(`第${index+2}行请选择特殊作业资质`)
          }
          let findItem = this.options.specialOperationEnum.find(item => specialJobType?.includes(item.label))
          return {
            name: item['姓名'],
            sex: item['性别'],
            telphone: item['手机号'],
            idCard: item['身份证号'],
            documentInfi: item['附件'],
            personSource: this.options.personSourceEnum[1].value,
            personType: this.personType,
            specialJobType: findItem?.value,
          }
        })

        let idCardPatter = /^(([1][1-5])|([2][1-3])|([3][1-7])|([4][1-6])|([5][0-4])|([6][1-5])|([7][1])|([8][1-2]))\d{4}(([1][9]\d{2})|([2]\d{3}))(([0][1-9])|([1][0-2]))(([0][1-9])|([1-2][0-9])|([3][0-1]))\d{3}[0-9xX]$/
        let phonePatter = /^1[3456789]\d{9}$/
        importList.forEach((item, index) => {
          this.validUser(item)
          this.validTableUser(item, index, importList)
          let idMatch = idCardPatter.test(item.idCard)
          if (!idMatch) {
            this.$message.error(`第${index+2}行请输入正确身份证号码`)
            throw new Error(`第${index+2}行请输入正确身份证号码`)
          }
          let phoneMatch = phonePatter.test(item.telphone)
          if (!phoneMatch) {
            this.$message.error(`第${index+2}行请输入正确手机号码`)
            throw new Error(`第${index+2}行请输入正确手机号码`)
          }
          if (!['男', '女'].includes(item.sex)) {
            this.$message.error(`第${index+2}行请选择性别`)
            throw new Error(`第${index+2}行请选择性别`)
          }
          if (!item.name) {
            this.$message.error(`第${index+2}行请输入姓名`)
            throw new Error(`第${index+2}行请输入姓名`)
          }
          // if (!this.notRequireFile && !item.documentInfi) {
          //   this.$message.error("请录入附件地址")
          //   throw new Error("请录入附件地址")
          // }
        })
        this.$emit('onsubmit', importList)
      }
      // 读取文件
      reader.readAsBinaryString(file);
    },
    validUser(addRow) {
      let find = this.operators.find(item => item.idCard === addRow.idCard)
      if (find) {
        this.$message.error("同一作业类型无法添加相同人员")
        throw new Error("同一作业类型无法添加相同人员")
      }
    },
    validTableUser(addRow, addIndex, importList) {
      let find = importList.find((item, index) => index !== addIndex && item.idCard === addRow.idCard)
      if (find) {
        this.$message.error("同一作业类型无法添加相同人员")
        throw new Error("同一作业类型无法添加相同人员")
      }
    }
  }
}
</script>

<style lang="less" scoped>
.user-table {
  padding-left: 50px;
  margin-bottom: 20px;

  .user-table-title-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;

    .table-title {
      font-size: 14px;
    }
  }
}
</style>
